import { Controller, Post, UseGuards, Request, Get, Body, Res } from '@nestjs/common';
import { Response } from 'express';
import { AuthService } from './auth.service';
import { LocalAuthGuard } from './local-auth.guard';
import { JwtAuthGuard } from './jwt-auth.guard';

@Controller('auth')
export class AuthController {
  constructor(private authService: AuthService) {}

  @UseGuards(LocalAuthGuard)
  @Post('login')
  async login(@Request() req, @Res() res: Response) {
    try {
      const data = await this.authService.login(req.user);
      
      // 设置 access_token cookie
      res.cookie('access_token', data?.access_token, {
        httpOnly: true,
        maxAge: 24 * 60 * 60 * 1000, // 24小时
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'strict',
      });

      // 设置用户信息 cookie
      res.cookie('user', JSON.stringify(data?.user), {
        httpOnly: true,
        maxAge: 24 * 60 * 60 * 1000, // 24小时
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'strict',
      });

      return res.status(200).json({
        retcode: 0,
        message: '登录成功',
        data,
      });
    } catch (error) {
      console.error('Login error:', error);
      return res.status(401).json({
        retcode: -1,
        message: error.message || '登录失败',
        data: null,
      });
    }
  }

  @UseGuards(JwtAuthGuard)
  @Get('profile')
  getProfile(@Request() req) {
    return req.user;
  }

  @UseGuards(JwtAuthGuard)
  @Post('refresh')
  async refreshToken(@Request() req) {
    return this.authService.refreshToken(req.user);
  }
} 